package be.ac.ua.ecampus.cmat;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ac.ua.ecampus.cmat.types.Program;
import be.ac.ua.ecampus.cmat.types.Syllabus;

@WebServlet(description = "Show", urlPatterns = { "/show" })
public class ShowServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public ShowServlet() {
        super();
    }
    
	public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		final String type = request.getParameter("type");
		final String id = request.getParameter("id");
		if ((id == null) || (type == null) || type.isEmpty() || id.isEmpty()) {
			System.out.println("[CMAT WARNING] - [SHOW] - Empty parameter.");
			return;
		}
			
		try {
			if (type.equalsIgnoreCase("program")) {
				this.showProgram(request, response, Integer.parseInt(id));
			} else if (type.equalsIgnoreCase("syllabus")) {
				this.showSyllabus(request, response, Integer.parseInt(id));
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * Get all info for a given program.
	 */
	public void showProgram(final HttpServletRequest request, final HttpServletResponse response, int id) throws SQLException, ServletException, IOException {
		QueryHandler queryHandler = new QueryHandler();
		Program program = queryHandler.getProgram(id);
		request.setAttribute("program", program);
    	request.getRequestDispatcher("/showProgram.jsp").forward(request, response);
	}
	
	/*
	 * Get all info for a given syllabus
	 */
	public void showSyllabus(final HttpServletRequest request, final HttpServletResponse response, int id) throws SQLException, ServletException, IOException {
		QueryHandler queryHandler = new QueryHandler();
		Syllabus syllabus = queryHandler.getSyllabus(id);
		request.setAttribute("syllabus", syllabus);
    	request.getRequestDispatcher("/showSyllabus.jsp").forward(request, response);
	}
}
